package com.hk.service.impl.view;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.hk.commons.HqlFilter;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.view.OrderView;
import com.hk.commons.entity.view.UserView;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.IOrganization;
import com.hk.service.sys.ISysUserRoles;
import com.hk.service.view.IOrderView;
import com.hk.service.view.IUserView;

@Service
public class OrderViewImpl extends BaseServiceImpl<OrderView> implements
		IOrderView {

	private Logger logger = LoggerFactory.getLogger(OrderViewImpl.class);

	@Autowired
	private IUserView userViewService;

	@Resource
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private ISysUserRoles roleService;

	@Autowired
	private IOrganization orgService;

	@Override
	public BigDecimal getCommission(Long orderId) {
		BigDecimal commission = new BigDecimal("0");
		// 佣金=产品购买金额*产品佣金比例*产品期限（天数）/365
		OrderView orderView = this.findById(orderId);
		if (orderView.getSuccessAmount() != null
				&& StringHelper.isNotEmpty(orderView.getCommissionRate())
				&& orderView.getProTerm() != null) {
			commission = orderView.getSuccessAmount()
					.multiply(new BigDecimal(orderView.getCommissionRate()))
					.multiply(new BigDecimal(orderView.getProTerm()))
					.divide(new BigDecimal("365"), 5);
		}
		return commission;

	}

	@Override
	public OrderView findById(long id) {
		return getById(id);
	}

	@Override
	public BigDecimal getAllCommission(HqlFilter hqlFilter) {
		BigDecimal allCommission = new BigDecimal("0");
		List<OrderView> list = this.findByFilter(hqlFilter);
		if (list.size() > 0) {
			for (OrderView view : list) {
				allCommission = allCommission.add(this.getCommission(view
						.getOrderId()));
			}
		}
		return allCommission;
	}

	@Override
	public BigDecimal getTotalCommByUser(Long userId, Integer commissionStatus) {

		String sql = "SELECT sum(commissionAmount) FROM orderView where userId = "
				+ userId;
		if (commissionStatus != null) {
			sql += " and commissionStatus = " + commissionStatus;
		}

		BigDecimal result = jdbcTemplate.queryForObject(sql, BigDecimal.class);

		if (result == null) {
			result = new BigDecimal("0.00");
		}

		return result;
	}

	@Override
	public BigDecimal getTotalCommByFinPhone(String finPhone,
			Integer commissionStatus) {
		String sql = "SELECT sum(commissionAmount) FROM orderView where finPhone = "
				+ finPhone;

		if (commissionStatus != null) {
			sql += " and commissionStatus = " + commissionStatus;
		}

		BigDecimal result = jdbcTemplate.queryForObject(sql, BigDecimal.class);

		if (result == null) {
			result = new BigDecimal("0.00");
		}

		return result;
	}

	@Override
	public List<OrderView> getAll(Long userId, String userRealName,
			String finUserRealName, String orderOrgName, Integer curPage,
			Integer pageSize, Integer reqType) {

		HqlFilter hqlFilter = getFilter(userId, userRealName, finUserRealName,
				orderOrgName, reqType);

		return findByFilter(hqlFilter, curPage, pageSize);
	}

	@Override
	public Long getSize(Long userId, String userRealName,
			String finUserRealName, String orderOrgName, Integer reqType) {
		HqlFilter hqlFilter = getFilter(userId, userRealName, finUserRealName,
				orderOrgName, reqType);

		return countByFilter(hqlFilter);
	}

	private HqlFilter getFilter(Long userId, String userRealName,
			String finUserRealName, String orderOrgName, int reqType) {

		HqlFilter hqlFilter = new HqlFilter();

		hqlFilter.addSql(" where 1=1");
		// 如果是手机端登录，只返回自己的订单订单数据
		if (reqType == 1) {

			hqlFilter.addSql(" where finUserId = " + userId + " )");
			return hqlFilter;
		}

		UserView userView = userViewService.findById(userId);

		if (userView == null || userView.getUserOrgId() == null) {
			logger.info("user is not exist userId={}", userId);
			return null;
		}

		// 如果不是运营部的人员，则添加筛选条件
		Boolean isOpear = roleService.isOperationalManager(userId);
		logger.info("userId ={}, isOpear = {}", userId, isOpear);

		if (!isOpear) {
			// 增加组织架构的筛选
			Organization org = orgService.findById(userView.getUserOrgId());
			// 如果用户的组织架构不为空，且为部门负责人
			if (org != null && org.getIsHeader() == 1) {
				String code = orgService.getOrgLeaderCodeByOrgId(org.getId());
				hqlFilter.addSql(" and ( finUserCode like '" + code + "%') ");
			} else {
				hqlFilter.addSql(" and financialPlannerId = " + userId + " )");
			}
		}

		if (StringHelper.isNotEmpty(userRealName)) {

			hqlFilter.addSql(" and (userRealName like '%" + userRealName
					+ "%' or userPhone like '%" + userRealName + "%') ");
		}

		if (StringHelper.isNotEmpty(orderOrgName)) {

			hqlFilter.addSql(" and (orderOrgName like '%" + orderOrgName
					+ "%' or orderOrgName like '%" + orderOrgName + "%') ");
		}

		if (StringHelper.isNotEmpty(finUserRealName)) {

			hqlFilter.addSql(" and (finPhone like '%" + finUserRealName
					+ "%' or finUserRealName like '%" + finUserRealName
					+ "%') ");
		}

		logger.info("hqlFilter = " + hqlFilter.getWhereAndOrderHql());
		return hqlFilter;
	}

}
